#include "test-item-infrared-lamp.h"

bool test_item_infrared_lamp_work_flag;

TestItemInfraredLamp::TestItemInfraredLamp()
{
}

TestItemInfraredLamp::~TestItemInfraredLamp()
{
}

void *infrared_lamp_work_pthread(void *arg)
{
    TestModuleFrameFormat *argFrameFormat = (TestModuleFrameFormat *)arg;
    uint8_t send_data[2];
    send_data[0] = TEST_INFRARED_LAMP;
    // int param_fd;
    // int switch_fd;

    //打开0号PWM通道信号
    system("echo 0 > /sys/class/pwm/pwmchip1/export");
    //设置PWM信号周期
    system("echo 10000000 >/sys/class/pwm/pwmchip1/pwm0/period");
    //设置PWM信号占空比
    system("echo 9000000 >/sys/class/pwm/pwmchip1/pwm0/duty_cycle");
    //使能0号通道PWM信号
    system("echo 1 >/sys/class/pwm/pwmchip1/pwm0/enable");
    //通过adwgpio设备文件控制红外灯的开启和关闭
    while(test_item_infrared_lamp_work_flag)
    {
        //开启红外灯
        system("echo b > /sys/devices/virtual/adw/adwdev/adwgpio");
        //保持1秒
        sleep(1);
        //关闭红外灯
        system("echo a > /sys/devices/virtual/adw/adwdev/adwgpio");
        //保持1秒
        sleep(1);
    }
    // close(param_fd);
    // close(switch_fd);
    send_data[1] = TEST_STOPED;
    argFrameFormat->framePackageFunction(send_data, sizeof(send_data));
    printf("红外灯测试线程退出！\n");
    return nullptr;
}

int TestItemInfraredLamp::recv_command_data(void *data, uint16_t length)
{
    if((NULL == data) || (length < 2))
    {
        printf("传入参数错误！\n");
        return -1;
    }

    int ret;
    uint8_t recvBuffer[length] = {0};
    uint8_t sendBuffer[2] = {0};
    sendBuffer[0] = TEST_INFRARED_LAMP;

    memcpy(recvBuffer, data, length);

    if(recvBuffer[1] == TEST_START)//开始
    {
        test_item_infrared_lamp_work_flag = true;
        ret = pthread_create(&work_pthread, NULL, infrared_lamp_work_pthread, (void *)&frameOperate);
        if(ret == -1)
        {
            printf("红外灯测试，创建线程失败！\n");
            return ret;
        }
        sendBuffer[1] = TEST_STARTED;
        frameOperate.framePackageFunction(sendBuffer, sizeof(sendBuffer));
        printf("红外灯测试开始！\n");
    }else if(recvBuffer[1] == TEST_STOP)//停止
    {
        test_item_infrared_lamp_work_flag = false;
        printf("红外灯测试结束！\n");
    }else
    {
        printf("数据错误：%x , %x \n", recvBuffer[0], recvBuffer[1]);
    }

    return 0;
}
